package com.lagou.edu.controller;

import com.lagou.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseCookie;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.resource.HttpResource;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yutao
 * @create 2020-07-05 12:12
 **/
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/register/{email}/{password}/{code}")
    public Boolean register(@PathVariable("email") String email, @PathVariable("password") String password, @PathVariable("code") String code) {
        return userService.register(email, password, code);
    }

    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable("email") String email) {
        return userService.isRegistered(email);
    }
    private final static String cookieKey = "lagou_cookie";

    @GetMapping("/login/{email}/{password}")
    public String login(HttpServletResponse response, @PathVariable("email") String email, @PathVariable("password") String password) {
        // 登陆后设置token
        String login = userService.login(email, password);
        if (!ObjectUtils.isEmpty(login)){
            String token = userService.token(email);
            Cookie cookie = new Cookie(cookieKey, token);
            cookie.setPath("/");
            cookie.setDomain("www.test.com");
            response.addCookie(cookie);
        }
        return login;
    }

    @GetMapping("/info")
    public String info(@CookieValue("lagou_cookie") String token) {
        return userService.info(token);
    }

    @GetMapping("/validToken/{token}")
    public Boolean validToken(@PathVariable(value = "token",required = false) String token){
        String email = info(token);
        if(!ObjectUtils.isEmpty(email)){
            return true;
        }
        return false;
    }

}
